<template>
<el-form label-width="80px">
  <el-form-item :label="$t('group.userGroup')">
    <el-select style="width: 80%;" v-model="leaders" multiple filterable remote :placeholder="$t('rule.keyword')" :remote-method="remoteLeaderMethod" :loading="loading">
      <el-option v-for="item in lItems" :key="item.id" :label="item.name" :value="item.id"> </el-option>
    </el-select>
  </el-form-item>
  <el-form-item :label="$t('group.groupType')">
    <el-select style="width: 80%;" v-model='groups'>
      <el-option
      v-for='item in roleType'
      :key='item.id'
      :label='item.dictValue'
      :value='item.id'>
      </el-option>
    </el-select>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" v-if="groupManager_btn_userManager" @click="onSubmit">{{$t('btn.conserve')}}</el-button>
  </el-form-item>
</el-form>
</template>

<script>
import {
  getByRoleId,
  modifiyGroups,
  getAllRoleTypes,
  getAllUserGroup
} from 'api/admin/group/index';
import { mapGetters } from 'vuex';
export default {
  props: {
    groupId: {
      default: '1'
    }
  },
  data() {
    return {
      lItems: [],
      roleType: [],
      leaders: [],
      groups: [],
      loading: false,
      groupManager_btn_userManager: false
    }
  },
  created() {
    this.initGroup();
    this.roleTypes();
    this.groupManager_btn_userManager = this.elements['groupManager:btn_userManager'];
    
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    remoteLeaderMethod(query) {
      if (query !== '') {
        this.loading = true;
        this.loading = false;
        getAllUserGroup({
          name: query
        }).then(response => {
          this.lItems = response;
          this.loading = false;
        });
      } else {
        this.lItems = [];
      }
    },
    onSubmit() {
      const vals = {};
      vals.groupId = this.leaders.join();
      vals.roleType = this.groups;
      vals.roleId = this.groupId;
      modifiyGroups(vals).then(() => {
        this.$emit('closeGroupDialog');
        this.$notify({
          title: this.$t('group.success'),
          message: this.$t('group.savesuccess'),
          type: 'success',
          duration: 2000
        });
      });
    },
    initGroup() {
      let obj = {};
      obj.roleId = this.groupId
      getByRoleId(obj).then(response => {
        this.lItems = response;
        let mems = [];
        let leas = [];
        response.forEach(item => {
          leas.push(item.id);
        })
        if (response.length > 0) {
          if ( response[0].attr1 === "null") {
            mems = '';
          } else {
            mems = Number(response[0].attr1);
          }
        } else {
          mems = '';
        }
        this.groups = mems;
        this.leaders = leas;
      });
    },
    // 组类型下拉
    roleTypes() {
      getAllRoleTypes()
      .then(res => {
        this.roleType = res
      })
    }
  }
}
</script>
